package com.bxs.sniffer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bxs.config.IdsConfig;
import com.bxs.handler.HandlerManager;
import com.bxs.pojo.FilterRule;
import lombok.extern.slf4j.Slf4j;
import org.pcap4j.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;


// 基类嗅探器：实现数据包的数据抓取
@Component
@Slf4j
public class BaseSniffer {
    @Autowired
    IdsConfig idsConfig;


    // 获取到数据包进行的处理器
    public HandlerManager handlerManager;

    // 默认参数
    protected int snapLen = IdsConfig.snapLen;
    protected int timeout = IdsConfig.timeout;
    protected int count = IdsConfig.count;

    // 抓包的网卡接口及句柄
    public PcapNetworkInterface networkInterface = null;
    public PcapHandle handle = null;
    // 数据包存储器
    public PcapDumper dumper = null;

    // 抓包过滤器管理器
    @Autowired
    public FilterManager filterManager;

    // 回调监听器
    public PacketListener callbackListener = null;

//    protected ExecutorService executorService = null;
    public ThreadPoolExecutor executorService = null;

    public BaseSniffer() throws PcapNativeException, UnknownHostException {
//        if(name == null){
//            List<PcapNetworkInterface> allDevs = Pcaps.findAllDevs();
//            for(PcapNetworkInterface pcapNetworkInterface : allDevs){
//                System.out.println(pcapNetworkInterface);
//            }
//        }
//        networkInterface = Pcaps.getDevByName(name);
//        monitorAddress = "192.168.1.101";
        // 从配置类中加载监听的网卡接口
   }

    // 启动嗅探器
    public void start() throws PcapNativeException, NotOpenException, InterruptedException, UnknownHostException {
        String name = idsConfig.interfaceAddressName;
        networkInterface = Pcaps.getDevByAddress(InetAddress.getByName(name));
        System.out.println("current listening network interface: " + networkInterface.getName() + " ; " + networkInterface.getAddresses());

        handle = networkInterface.openLive(snapLen, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, timeout);
        log.info("open network interface success");
        // 加载过滤规则
        System.out.println("filterManager:" + filterManager);
        List<FilterRule> filterRules = filterManager.getFilters(new QueryWrapper<>());
        System.out.println("filter rules: " + filterRules);
        for(FilterRule rule : filterRules){
            handle.setFilter(rule.getCont(), BpfProgram.BpfCompileMode.OPTIMIZE);
        }
        // 开启dumper存储数据包到文件
        openPacpDumper(idsConfig.defaultFile);
        // 开启回调监听循环
        if(idsConfig.isSave){
            System.out.println("start loop...");
            handle.loop(count, callbackListener);     // 写入文件的话不能在嗅探器分发线程，会出现文件写入不一致（使用锁代价太大）
        }else {
            // 不写入文件时分发线程进行处理
//            executorService = Executors.newFixedThreadPool(10);
            handle.loop(count, callbackListener, executorService);
        }
        System.out.println("start execute finished");
    };

    // 关闭嗅探器
    public void stop() throws NotOpenException{
        System.out.println("start stop handle");
        if(handle != null) {
            handle.breakLoop();
            handle.close();
        }
        if(executorService != null) executorService.shutdown();
        if (dumper != null)dumper.close();
        System.out.println("stop handle finished");
    }

    // 文件写入器
    public void openPacpDumper(String filename) throws PcapNativeException, NotOpenException {
        if (handle == null) throw new NullPointerException("sniffer not start, null");
        if (idsConfig.isSave) dumper = handle.dumpOpen(filename);
        handlerManager.packetDumper = dumper;
    }

    public void setHandlerManager(HandlerManager handlerManager){
        this.handlerManager = handlerManager;
    }

    public Map<String, Object> getPacketInfo() throws NotOpenException, PcapNativeException {
        if(!handle.isOpen())return null;
        Map<String, Object> map = new HashMap<>();
        PcapStat stats = handle.getStats();
        map.put("receive", stats.getNumPacketsReceived());
        map.put("captured", stats.getNumPacketsCaptured());
        map.put("dropped", stats.getNumPacketsDropped());
        return map;
    }

}
